<template>
  <div class="announcements-container">
    <h2 class="page-title">公告管理</h2>
    
    <!-- 筛选和搜索 -->
    <el-card shadow="hover" class="filter-container">
      <div slot="header" class="clearfix">
        <span>公告列表</span>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">
          发布公告
        </el-button>
      </div>
      
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="公告类型">
          <el-select v-model="queryParams.type" placeholder="全部" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="通知" value="通知"></el-option>
            <el-option label="维护" value="维护"></el-option>
            <el-option label="活动" value="活动"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="草稿" value="0"></el-option>
            <el-option label="已过期" value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="搜索">
          <el-input v-model="queryParams.keyword" placeholder="标题/内容" clearable>
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>


      <!-- 批量删除按钮 -->
      <el-button type="danger" size="small" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>


      <!-- 公告列表表格 -->
      <el-table
        v-loading="loading"
        :data="announcementList"
        border
        stripe
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="标题" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template slot-scope="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)" size="small">
              {{ getPriorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="createdAt" label="创建时间" width="160"></el-table-column> -->
        <el-table-column prop="startTime" label="生效时间" width="160"></el-table-column>
        <el-table-column prop="endTime" label="过期时间" width="160"></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="阅读量" width="80" align="center"></el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="primary" 
              icon="el-icon-view" 
              @click="handleView(scope.row)"
              title="查看">
            </el-button>
            <el-button 
              size="mini" 
              type="success" 
              icon="el-icon-edit" 
              @click="handleUpdate(scope.row)"
              title="编辑">
            </el-button>
            <el-button
              v-if="scope.row.status != 1"
              size="mini"
              type="info"
              icon="el-icon-upload2"
              @click="handlePublish(scope.row)"
              title="发布">
            </el-button>
            <el-button
              v-else
              size="mini"
              type="warning"
              icon="el-icon-download"
              @click="handleUnpublish(scope.row)"
              title="取消发布">
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              title="删除">
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 添加/编辑公告对话框 -->
    <announcement-form
      :visible.sync="formDialogVisible"
      :title="formDialogTitle"
      :announcement="selectedAnnouncement"
      @success="handleFormSuccess"
    />
    
    <!-- 查看公告详情对话框 -->
    <announcement-detail
      :visible.sync="detailDialogVisible"
      :announcement="selectedAnnouncement"
    />
  </div>
</template>

<script>
import announcementApi from '@/api/announcement'
import AnnouncementForm from './components/AnnouncementForm'
import AnnouncementDetail from './components/AnnouncementDetail'

export default {
  name: 'Announcements',
  components: {
    AnnouncementForm,
    AnnouncementDetail
  },
  data() {
    return {
      // 加载状态
      loading: false,
      // 公告列表
      announcementList: [],
      // 总记录数
      total: 0,
      // 选中的行
      selectedRows: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        type: '',
        status: ''
      },
      // 对话框显示状态
      formDialogVisible: false,
      detailDialogVisible: false,
      // 对话框标题
      formDialogTitle: '',
      // 当前选中的公告
      selectedAnnouncement: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {

    // 批量删除
    handleBatchDelete() {

      this.$confirm('此操作将永久删除该数据吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {


        const ids = this.selectedRows.map(row => row.id)
        announcementApi.deleteAnnouncements(ids).then(response => {
              if (response.code === 1) {
                this.$message.success('删除成功')
                this.getList()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }




        });


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });




    },
    
    // 获取公告列表
    getList() {
      this.loading = true
      announcementApi.getAnnouncements(this.queryParams).then(response => {
        if (response.code === 1) {
          // 兼容两种后端返回格式：rows 或 list
          const listData = response.data.rows || response.data.list || []
          // 格式化数据，统一字段名
          this.announcementList = listData.map(item => this.formatData(item))
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '获取公告列表失败')
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    
    // 格式化数据，确保字段命名一致
    formatData(data) {
      const item = { ...data }
      
      // 下划线命名转驼峰
      if (item.created_at !== undefined && !item.createdAt) item.createdAt = item.created_at
      if (item.updated_at !== undefined && !item.updatedAt) item.updatedAt = item.updated_at
      if (item.start_time !== undefined && !item.startTime) item.startTime = item.start_time
      if (item.end_time !== undefined && !item.endTime) item.endTime = item.end_time
      if (item.view_count !== undefined && !item.viewCount) item.viewCount = item.view_count
      if (item.publisher_id !== undefined && !item.publisherId) item.publisherId = item.publisher_id
      
      return item
    },
    
    // 搜索按钮
    handleSearch() {
      this.queryParams.pageNum = 1
      // console.log('搜索按钮', this.queryParams)
      this.getList()
    },
    
    // 重置按钮
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        type: '',
        status: ''
      }
      this.getList()
    },
    
    // 选择项变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    // 每页显示条数变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    
    // 添加公告
    handleAdd() {
      this.selectedAnnouncement = {}
      this.formDialogTitle = '发布公告'
      this.formDialogVisible = true
    },
    
    // 查看公告详情
    handleView(row) {
      this.selectedAnnouncement = row
      this.detailDialogVisible = true
    },
    
    // 修改公告
    handleUpdate(row) {
      this.selectedAnnouncement = JSON.parse(JSON.stringify(row))
      this.formDialogTitle = '编辑公告'
      this.formDialogVisible = true
    },
    
    // 发布公告
    handlePublish(row) {
      this.$confirm('确认要发布该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        announcementApi.setAnnouncementStatus(1, row.id).then(response => {
          if (response.code === 1) {
            this.$message.success('发布成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '发布失败')
          }
        })
      }).catch(() => {})
    },
    
    // 取消发布
    handleUnpublish(row) {
      this.$confirm('确认要取消发布该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        announcementApi.setAnnouncementStatus(0, row.id).then(response => {
          if (response.code === 1) {
            this.$message.success('取消发布成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '取消发布失败')
          }
        })
      }).catch(() => {})
    },
    
    // 删除公告
    handleDelete(row) {
      this.$confirm('确认要删除该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = [row.id]
        announcementApi.deleteAnnouncements(ids).then(response => {
          if (response.code === 1) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        })
      }).catch(() => {})
    },
    
    // 表单提交成功
    handleFormSuccess() {
      this.getList()
    },
    
    // 获取公告类型标签样式
    getTypeTagType(type) {
      const typeMap = {
        '通知': 'primary',
        '维护': 'info',
        '活动': 'success',
        '其他': 'warning'
      }
      return typeMap[type] || ''
    },
    
    // 获取状态标签样式
    getStatusTagType(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'warning'
      }
      return statusMap[status] || ''
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '草稿',
        1: '已发布',
        2: '已过期'
      }
      return statusMap[status] || status
    },
    
    // 获取优先级标签样式
    getPriorityTagType(priority) {
      const priorityMap = {
        0: 'info', // 普通
        1: 'warning', // 重要
        2: 'danger' // 紧急
      }
      return priorityMap[priority] || 'info'
    },
    
    // 获取优先级文本
    getPriorityText(priority) {
      const priorityMap = {
        0: '普通',
        1: '重要',
        2: '紧急'
      }
      return priorityMap[priority] || '普通'
    }
  }
}
</script>

<style scoped>
.announcements-container {
  padding-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-container .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 